#include <QString>
#include <glog/logging.h>

#include "util/utils.h"
#include "mqtt/mqtt_client_thread.h"

MqttClient::MqttClient(const char *id, const char *topic, const char *host, int port) : mosquittopp(id)
{
    config.id = id;
    config.topic = QString("%1").arg(topic);
    config.host = host;
    config.port = port;
    config.keepalive = 60;
}

MqttClient::~MqttClient() {}

MqttConfig* MqttClient::get_config() {
    return &config;
}

void MqttClient::connect_broker() {
    LOG(INFO) << "---------------------------------------";
    LOG(INFO) << "connect to" << config.host.toStdString() << config.port;
    const char *host = config.host.toLatin1().data();
    connect(host, config.port, config.keepalive);
}

void MqttClient::subscribe_topic() {
    const char *topic =  Utils::str_to_char_array(config.topic);
    LOG(INFO) << "MqttClient | subscribe_topic | topic=" << topic;
    subscribe(NULL, topic);
    delete []topic;
}

void MqttClient::publish_topic(void *payload, long payload_len, bool retain) {
    const char *topic =  Utils::str_to_char_array(config.topic);
    LOG(INFO) << "MqttClient | publish_topic | topic" << topic;
    publish(NULL, topic, payload_len, payload, 0, retain);
    delete []topic;
}

MqttClientThread::MqttClientThread(MqttClient *client) {
    this->client = client;
}

MqttClient* MqttClientThread::get_client() {
    return this->client;
}

void MqttClientThread::run() {
    this->client->connect_broker();
    int rc = 0;
    while (true) {
        rc = this->client->loop();
        if (rc) {
            LOG(INFO) << "topic" << this->client->get_config()->topic.toStdString() << "reconnect";
            this->client->reconnect();
        }
    }
}
